import threading
import Queue
import time

SUCCESS = 0
class MdssyncStatus(object):
    """
    MdssyncStatus
    """
    NO_START     = 0
    RUNNING      = 1
    SUCCESS_END  = 2
    ERR          = 3
    def __init__(self, status = 0, errcode = SUCCESS, errmessage = ""):
        self.status = status
        self.errcode = errcode
        self.errmessage = errmessage


class MdssyncThread(threading.Thread):
    """
    Base thread model
    """
    def __init__(self):
        threading.Thread.__init__(self)
        self.threadstatus = MdssyncStatus()
        self.mutux = threading.Lock()
        self.setDaemon(True)
        self.__stop_event = threading.Event()

    def get_thread_status(self):
        return self.threadstatus

    def set_thread_status(self, status = None, errcode = None, errmessage = None):
        self.mutux.acquire()
        if status != None:
            self.threadstatus.status = status
        if errcode != None:
            self.threadstatus.errcode = errcode
        if errmessage != None:
            self.threadstatus.errmessage = errmessage
        self.mutux.release()

    def stop(self):
        """
        stop thread
        """
        print "stop"
        self.__stop_event.set()

class Log(MdssyncThread):

    def __init__(self, work_queue, result_queue):
        MdssyncThread.__init__(self)
        self.work_queue = work_queue
        self.result_queue = result_queue

    def start(self):
        print "start"
        self.set_thread_status(status = MdssyncStatus.RUNNING)
        super(Log, self).start()

    def run(self):
        while True:
            job = self.work_queue.get(True)
            print job
            if job == None:
                print "end"
                self.set_thread_status(status = MdssyncStatus.SUCCESS_END)
                break
            if job == 18:
                print "error"
                self.set_thread_status(MdssyncStatus.ERR, 1, "err happen")
                break
            self.result_queue.put(job)

        self.result_queue.put(None)

work_queue = Queue.Queue()
result_queue = Queue.Queue()
Logger1 = Log(work_queue, result_queue)
Logger2 = Log(work_queue, result_queue)
for i in range(15):
    work_queue.put(i)

work_queue.put(None)

Logger1.start()
Logger2.start()

print "start check status"
time.sleep(10)


while True:
    threadstatus = Logger.get_thread_status()
    if threadstatus.status == MdssyncStatus.ERR:
        print threadstatus.errcode, threadstatus.errmessage
        break
    if threadstatus.status == MdssyncStatus.SUCCESS_END:
        print "SUCCESS_END"
        break

    time.sleep(10)

Logger.stop()

while True:
    value = result_queue.get(True)
    print value
    if value == None:
        break